from rest_framework import pagination
from rest_framework.response import Response
from rest_framework import serializers
from ability.enums import *
from rest_framework.views import exception_handler, set_rollback
from django.http import Http404
from rest_framework import exceptions
from django.core.exceptions import PermissionDenied
from django.conf import settings
from ability.cloud import CosClient

class CustomPagination(pagination.PageNumberPagination):
    page_size_query_param = 'page_size'
    def get_paginated_response(self, data):
        return Response({
            "error_code": 0,
            'total_records': self.page.paginator.count,
            'data': data
        })

class FormatTransField(serializers.CharField):
    def __init__(self, **kwargs):
        self.transname = kwargs.pop('transname', False)
        super().__init__(**kwargs)
    def to_representation(self, value):
        try:
            objdict = eval('trans.' + self.transname)
            val = list(objdict.keys())[list(objdict.values()).index(str(value))]
            return int(val)
        except Exception as e:
            return 0

class FormatTransLabelField(serializers.CharField):
    def __init__(self, **kwargs):
        self.transname = kwargs.pop('transname', False)
        super().__init__(**kwargs)
    def to_representation(self, value):
        try:
            objdict = eval('trans.' + self.transname)
            for v, k in objdict.items():
                if value == k:
                    return v
            return '未知'
        except Exception as e:
            print(str(e))
            return '未知'

class ReverseFormatTransField(serializers.CharField):
    def __init__(self, **kwargs):
        self.transname = kwargs.pop('transname', False)
        super().__init__(**kwargs)
    def to_representation(self, value):
        objdict = eval('trans.' + self.transname)
        val = objdict[value]
        return str(val)

def GetPostParaOrNone(object1, name, default=None):
    if name in object1 and object1[name] != None:
        return object1[name]
    else:
        return default

class CustomResponse(object):
    def __init__(self, **args):
        self.response = {
            "error_code": args.get('error', 0),
            "message": args.get('message', 'success'),
            "data": args.get('data', [])
        }

def custom_exception_handler(exc, context):

    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # Now add the HTTP status code to the response.
    if response is not None:
        response.data['error_code'] = response.status_code
        response.data['message'] = response.data['detail']
        del response.data['detail']

    return response

def sign_rich_attach_url(location):
    if settings.MEDIA_STORAGE == 'cos':
        cosClient = CosClient()
        return cosClient.get_presigned_url(location)
    else:
        return settings.MEDIA_HOST + location 

def sign_attach_url(location):
    return settings.MEDIA_HOST + location 
